import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Row, Input, Button, Col, Modal, Icon, Select, Divider, Form, Radio, Cascader, Alert } from 'antd';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import OptionInput from '@/components/OptionInput'
import FillInItemModal from './FillInItemModal'
import SingleLevelOption from './SingleLevelOption'
import styles from './style.less';
import {isEmpty} from '@/utils/utils';

const Option = Select.Option;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
let id = 1;

@connect(({ settings }) => ({
  fillInItemList:settings.fillInItemList,
  singleLevelOptionList:settings.singleLevelOptionList,
  doubleLevelOptionList:settings.doubleLevelOptionList
}))
@Form.create()
class EnteredSetting extends PureComponent {
  state = {
    writeModalVisible: false,
    oneSelectModalVisible: false,
    doubleSelectModalVisible: false,
    confirmLoading: false,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'settings/getSignUpInfo',
    });
  }

  handleCancel = () => {
    this.setState({
      writeModalVisible: false,
      oneSelectModalVisible: false,
      doubleSelectModalVisible: false,
    });
  }

  showModal = key => {
    switch (key) {
      case 'write':
        this.setState({ writeModalVisible: true });
        break;
      case "one":
        this.setState({ oneSelectModalVisible: true });
        break;
      case "two":
        this.setState({ doubleSelectModalVisible: true });
        break;
      default: break;
    }
  };

  showCallBack=()=>{
    this.setState({
      writeModalVisible: false,
      oneSelectModalVisible: false,
      doubleSelectModalVisible: false,
    });
  }

  handleSubmit = (e) => {
    const { form, dispatch } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        this.setState({
          confirmLoading: true,
        });
        dispatch({
          type: 'settings/setDoubleOption',
          payload: values,
          callback: (res) => {
            if (res) {
              this.setState({
                confirmLoading: false,
              });
              this.handleCancel()
            }
          }
        })
      }
    });
  }

  handleOk = (e) => {
    this.handleSubmit(e);
  }

  handleClick = (id) => {
    console.log(id)
    const { dispatch } = this.props;
    dispatch({
      type: 'settings/deleteOption',
      payload: {
        optionId: id
      }
    })
  }

  formRemove = (k) => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    // We need at least one passenger
    if (keys.length === 2) {
      return;
    }
    // can use data-binding to set
    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
  }

  formAdd = () => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    const nextKeys = keys.concat(id+=1);
    // can use data-binding to set
    // important! notify form to detect changes
    form.setFieldsValue({
      keys: nextKeys,
    });
  }

  checkOptionInput = (rule, value, callback) => {
    // console.log(value)
    if (value!==undefined&&!isEmpty(value.firstOption)&&!isEmpty(value.secondOption)
        ) {
      callback();
      return;
    }
    callback('一级选项和二级选择均不能为空');
  }

  render() {
    const { writeModalVisible, oneSelectModalVisible, doubleSelectModalVisible, confirmLoading } = this.state
    const {
      form: { getFieldDecorator, getFieldValue },
      fillInItemList, singleLevelOptionList, doubleLevelOptionList
    } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 19, offset: 3 },
      },
    };
    getFieldDecorator('keys', { initialValue: [0,1] });
    const keys = getFieldValue('keys');
    const formItems = keys.map((k, index) => (
      <FormItem
        {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
        label={index === 0 ? '选项' : ''}
        required
        key={k}
      >
        {getFieldDecorator(`option[${k}]`, {
          validateTrigger: ['onChange', 'onBlur'],
          rules: [{
            validator: this.checkOptionInput
          }],
        })(
          <OptionInput />
        )}
        {keys.length > 2 ? (
          <Icon
            // className="dynamic-delete-button"
            type="minus-circle-o"
            disabled={keys.length === 2}
            onClick={() => this.formRemove(k)}
            style={{marginLeft:10,color:`red`}}
          />
        ) : null}
      </FormItem>
    ))
    const fillInItem = fillInItemList.length>0&&fillInItemList.map((value,index) => (
      <Col style={{marginBottom:5,marginTop:5}} lg={8} md={8} sm={24} key={index}>
        <span className={styles.showSpan}>{value.title}</span> : 
        <Input key={value} style={{width:`90%`}} />
        <Icon onClick={()=>this.handleClick(value.id)} style={{marginLeft:8,color:`red`}} type="close-circle" />
      </Col>
    ))
    const singleLevelOption = singleLevelOptionList.length>0&&singleLevelOptionList.map((value,index) => (
      <Col style={{marginBottom:5,marginTop:5}} lg={8} md={8} sm={24} key={index}>
        <span className={styles.showSpan}>{value.title}</span> : 
        <Select defaultValue={value.option[0]} style={{width:`90%`}}>
          {value.option.map((value1,index1)=>(
            <Option key={index1} value={value1}>{value1}</Option>
          ))}
        </Select>
        <Icon onClick={()=>this.handleClick(value.id)} style={{marginLeft:8,color:`red`}} type="close-circle" />
      </Col>
    ))
    const doubleLevelOption = doubleLevelOptionList.length>0&&doubleLevelOptionList.map((value,index) => (
      <Col style={{marginBottom:5,marginTop:5}} lg={8} md={8} sm={24} key={index}>
        {/* {value.title} : 
        {console.log(value)}
        <Select style={{ width: `100%` }}>
          {value.option.map((value,index) => (
            <Option  key={index} value={value.firstOption}>{value.firstOption}</Option>
          ))}
        </Select>
        <Select></Select> */}
        <span className={styles.showSpan}>{value.title}</span> : 
        <Cascader style={{width:`90%`}} options={value.option} />
        <Icon onClick={()=>this.handleClick(value.id)} style={{marginLeft:8,color:`red`}} type="close-circle" />
      </Col>
    ))

    return (
      <GridContent>
        <Card title="用户报名信息设置" className={styles.card}>
          <Row gutter={24}>
            <Col xs={24} md={14} lg={16}>
              <Card title="报名信息采集表 -- 预览" className={styles.showCard}>
                <Row gutter={24}>
                  <h3>填写项</h3>
                  {fillInItem}
                </Row>
                <Divider dashed className={styles.showDivider} />
                <Row gutter={24}>
                  <h3>单级选择项</h3>
                  {singleLevelOption}
                </Row>
                <Divider dashed className={styles.showDivider} />
                <Row gutter={24}>
                  <h3>双级选择项</h3>
                  {doubleLevelOption}
                </Row>
              </Card>
            </Col>
            <Col xs={24} md={10} lg={8}>
              <Card title="请添加您要收集的参赛信息" bordered={false}>
                <div style={{ marginBottom: 5 }}>
                  <div className={styles.showDiv}>填写项</div>
                  {/* <div className={styles.showDivChildren}>不支持个性化统计及分组排行</div> */}
                </div>
                <div style={{ marginTop: 10 }}>
                  <div className={styles.showDivChildren}>示例：</div>
                  <span>姓名</span>
                  <div className={styles.showDivChildren} style={{ borderBottom: `1px solid` }}>请输入您的姓名</div>
                </div>
                <div className={styles.showButton}><Button type="primary" onClick={() => this.showModal("write")}>+ 填写项</Button></div>
                {/* <Divider dashed className={styles.showDivider} />
                <div style={{ marginBottom: 5 }}>
                  <div className={styles.showDiv}>上传项</div>
                </div>
                <div style={{ marginTop: 10 }}>
                  <div className={styles.showDivChildren}>示例：</div>
                  <div className={styles.showDivChildren} style={{ border: `1px solid` }}>点击上传</div>
                </div>
                <div className={styles.showButton}><Button type="primary" onClick={() => this.showModal("write")}>+ 上传项</Button></div>
                <Divider dashed className={styles.showDivider} /> */}
                <div className={styles.showDiv}>单级选项</div>
                {/* <div className={styles.showDivChildren}>支持个性化统计及大赛分组排行</div> */}
                <div style={{ marginTop: 10 }}>
                  <div className={styles.showDivChildren}>示例：</div>
                  <span>单位</span>
                  <div className={styles.showDivChildren} style={{ border: `1px solid`, padding: 6 }}>请选择你的学校&nbsp;&nbsp;<Icon type="down" /></div>
                </div>
                <div className={styles.showButton}><Button type="primary" onClick={() => this.showModal("one")}>+ 单级选项</Button></div>
                <Divider dashed className={styles.showDivider} />
                <div className={styles.showDiv}>双级选项</div>
                {/* <div className={styles.showDivChildren}>支持个性化统计及大赛分组排行</div> */}
                <div style={{ marginTop: 10 }}>
                  <div className={styles.showDivChildren}>示例：</div>
                  <span>班级</span>
                  <div className={styles.showDivChildren} style={{ border: `1px solid`, padding: 6 }}>请选择年级&nbsp;&nbsp;<Icon type="down" /></div>
                  <div className={styles.showDivChildren} style={{ border: `1px solid`, padding: 6 }}>请选择班级&nbsp;&nbsp;<Icon type="down" /></div>
                </div>
                <div className={styles.showButton}><Button type="primary" onClick={() => this.showModal("two")}>+ 双级选项</Button></div>
              </Card>
            </Col>
          </Row>

          <FillInItemModal key={"fill"} callback={this.showCallBack} writeModalVisible={writeModalVisible} />
          
          <SingleLevelOption key={"single"} callback={this.showCallBack} oneSelectModalVisible={oneSelectModalVisible} />
          
          <Modal
            title="填写项"
            visible={doubleSelectModalVisible}
            width={600}
            confirmLoading={confirmLoading}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
          >
            <Form {...formItemLayout} onSubmit={this.handleSubmit}>
              <Row gutter={24}>
                <Col md={24}>
                  <Alert message="提示信息 : 用于添加（专业，等有二级选项的信息），在下方标题空填写所需收集的信息项的标题，第一个空填入一级选项，第二个空填入二级选项，选项以英文逗号分隔" type="info" />
                </Col>
              </Row>
              <div style={{height:45}} />
              <FormItem label="标题">
                {getFieldDecorator('title', {
                  rules: [
                    {
                      required: true,
                    }
                  ]
                })(<Input />)}
              </FormItem>
              <Row gutter={24}>
                <Col offset={4} lg={4}>一级选项</Col>
                <Col offset={2} lg={12}>二级选项，选项以中英文逗号区分</Col>
              </Row>
              {formItems}
              <FormItem {...formItemLayoutWithOutLabel}>
                <Button type="dashed" onClick={this.formAdd} style={{ width: '35%' }}>
                  <Icon type="plus" />添加一级选项
                </Button>
              </FormItem>
              <FormItem label="类型">
                {getFieldDecorator('type', {
                      rules: [
                        {
                          required: true,
                        }
                      ],
                      initialValue: 1
                    })(
                      <RadioGroup name="radiogroup">
                        <Radio value={1}>必填</Radio>
                        <Radio value={2}>选填</Radio>
                      </RadioGroup>)}
              </FormItem>
            </Form>
          </Modal>
        </Card>
      </GridContent>
    )
  }
}
export default EnteredSetting
